import Link from "next/link"
import classNames from "classnames"
import styles from './index.module.css'
import { useRef } from "react"
import anime from 'animejs'
import { usePathname } from "next/navigation"

export type Rect2 = {
  x: number,
  y: number
}

interface NavItemProps {
  path: string,
  title: string,
  children?: JSX.Element,
  menuWidth?: number
}

const NavItem: React.FC<NavItemProps> = ({
  path,
  title,
  children,
  menuWidth = 400
}) => {
  const pathname = usePathname();
  const menuRef = useRef<HTMLDivElement>(null);
  const animeRef = useRef<anime.AnimeInstance>();

  function onMouseEnter(e: React.MouseEvent) {
    const targetElm = e.target as Element;
    const { y, height, width } = targetElm.getBoundingClientRect();

    if (menuRef.current) {
      const x = (width - menuWidth) / 2;
      menuRef.current.style.left = x +'px';
      menuRef.current.style.top = y+height+'px';
      menuRef.current.style.display = 'block';
      
      animeRef.current = anime({
        targets: menuRef.current,
        height: [0, '140px'],
        opacity: [0, 1],
        duration: 200,
        autoplay: true,
        easing: 'easeInOutQuad',
      })
    }
  }

  function onMouseLeave(e: React.MouseEvent) {
    if (menuRef.current) {
      if (animeRef.current) {
        animeRef.current.pause(); 
      }
      
      menuRef.current.style.display = 'none'
    }
  }

  return (
      <li 
      className={classNames(pathname === path && styles.actived)} 
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
      >
        <Link href={path} className='text-gray-100 font-medium'>{title}</Link>
        {
          children && (
            <div className="absolute min-h-[100px] bg-white hidden z-50" style={{width: `${menuWidth}px`}} ref={menuRef}>
              { children }
            </div>
          )
        }
      </li>
  )
}

export default NavItem